<template>

<!-- 先判断 roleName 是否有值，无值时显示加载中 -->
<div v-if="!roleName">
  <el-loading v-loading="true" element-loading-text="加载中...">
    <div style="height: 1000px;"></div> <!-- 占位高度，避免布局抖动 -->
  </el-loading>
</div>

  <div class="other" v-if="roleName === '护理员'">
    <div class="result">
      <h2>审批结果</h2>
    </div>
    <div class="ca">
      <img src="/src/assets/images/注意1.png">
      <div>
        <h3>{{ isRejected ? '已拒绝' : '审批中' }}</h3>
      </div>
      <div class="oth">{{ isRejected ? '抱歉，您的退住申请已被拒绝。如有疑问，请联系相关审批人员。' : '稍等，退住申请单正在审批中，若该申请单长时间未处理，请联系(审批角色)！' }}</div>
      <!-- 操作记录区域 -->
      <el-card class="operation-record-card" :class="{ 'rejected-record-card': isRejected }">
        <div class="record-header">
          <h3>操作记录</h3>
          <div class="record-status">
            <span class="status-badge" :class="isRejected ? 'rejected' : 'processing'">
              {{ isRejected ? '已拒绝' : '审批中' }}
            </span>
          </div>
        </div>
        <div class="record-timeline">
          <div class="timeline-item completed">
            <div class="timeline-dot">
              <el-icon color="#67c23a" size="16">
                <Check />
              </el-icon>
            </div>
            <div class="timeline-content">
              <div class="timeline-title">发起申请</div>
              <div class="timeline-desc">申请退住</div>
              <div class="timeline-user">{{ form.applyName || '未知用户' }} (已发起)</div>
              <div class="timeline-time">{{ form.applyTime || '-' }}</div>
            </div>
          </div>
          
          <div class="timeline-item" :class="isRejected ? 'rejected' : 'processing'">
            <div class="timeline-dot">
              <el-icon :color="isRejected ? '#f56c6c' : '#409eff'" size="16">
                <Close v-if="isRejected" />
                <Clock v-else />
              </el-icon>
            </div>
            <div class="timeline-content">
              <div class="timeline-title">审批处理</div>
              <div class="timeline-desc">{{ isRejected ? '申请审批（已拒绝）' : '申请审批' }}</div>
              <div class="timeline-user">{{ isRejected ? (form.approver || '审批员') + ' (已拒绝)' : '审批员B (审批中)' }}</div>
              <div class="timeline-time">{{ isRejected ? (form.approveTime || '已拒绝') : '等待处理中...' }}</div>
              <div class="timeline-opinion" v-if="isRejected && approvalForm.approvalOpinion">
                <div class="timeline-opinion-label">拒绝原因：</div>
                <div class="timeline-opinion-text">{{ approvalForm.approvalOpinion }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>


  <div class="approval-page" v-else>
    <div class="content-wrapper">
      <div class="left-content">
        <!-- 基本信息区域 -->
        <el-card class="basic-info-card">
          <h3>基本信息</h3>
          <ul class="info-list">
            <li><span class="label">老人姓名</span><span class="value">{{ form.elderName || '-' }}</span></li>
            <li><span class="label">老人身份证号</span><span class="value">{{ form.idCard || '-' }}</span></li>
            <li><span class="label">联系方式</span><span class="value">{{ form.phone || '-' }}</span></li>
            <li><span class="label">费用期限</span><span class="value">{{ form.feePeriod || '-' }}</span></li>
            <li><span class="label">护理等级</span><span class="value">{{ form.nursingLevel || '-' }}</span></li>
            <li><span class="label">入住床位</span><span class="value">{{ form.bed || '-' }}床位</span></li>
            <li><span class="label">签约合同</span><span class="value">{{ form.contract || '-' }} <a href="#"
                  class="view-link">查看</a></span></li>
            <li><span class="label">养老顾问</span><span class="value">{{ form.advisor || '-' }}</span></li>
            <li><span class="label">护理员</span><span class="value">{{ form.nurse || '-' }}</span></li>
          </ul>
        </el-card>

        <!-- 申请信息区域 -->
        <el-card class="apply-info-card">
          <h3>申请信息</h3>
          <ul class="info-list">
            <li><span class="label">退住日期</span><span class="value">{{ form.checkoutDate || '-' }}</span></li>
            <li><span class="label">退住原因</span><span class="value">{{ formatReason(form.reason) || '-' }}</span></li>
            <li><span class="label">备注</span><span class="value">{{ form.remark || '-' }}</span></li>
            <li><span class="label">申请人</span><span class="value">{{ form.applyName || '-' }}</span></li>
            <li><span class="label">申请时间</span><span class="value">{{ form.applyTime || '-' }}</span></li>
          </ul>
        </el-card>
      </div>

      <div class="right-content">
                 <!-- 审批结果区域 -->
         <el-card class="approval-result-card" :class="{ 'rejected-card': isRejected }">
           <h3>审批结果</h3>
           <el-form :model="approvalForm" ref="approvalFormRef" label-width="120px">
             <el-form-item label="审批结果" prop="approvalResult"
               :rules="[{ required: true, message: '请选择审批结果', trigger: 'change' }]">
               <el-radio-group v-model="approvalForm.approvalResult" :disabled="isRejected">
                 <el-radio label="approvalPass">审批通过</el-radio>
                 <el-radio label="approvalReject">审批拒绝</el-radio>
                 <el-radio label="return">驳回</el-radio>
               </el-radio-group>
             </el-form-item>
             <el-form-item label="审批意见" prop="approvalOpinion"
               :rules="[{ required: true, message: '请输入审批意见', trigger: 'blur' }]">
               <el-input 
                 v-model="approvalForm.approvalOpinion" 
                 type="textarea" 
                 placeholder="请输入" 
                 maxlength="200"
                 show-word-limit
                 :disabled="isRejected"></el-input>
             </el-form-item>
           </el-form>
         </el-card>

                 <!-- 操作记录区域 -->
         <el-card class="operation-record-card" :class="{ 'rejected-record-card': isRejected }">
           <div class="record-header">
             <h3>操作记录</h3>
             <div class="record-status">
               <span class="status-badge" :class="isRejected ? 'rejected' : 'processing'">
                 {{ isRejected ? '已拒绝' : '审批中' }}
               </span>
             </div>
           </div>
           <div class="record-timeline">
             <div class="timeline-item completed">
               <div class="timeline-dot">
                 <el-icon color="#67c23a" size="16">
                   <Check />
                 </el-icon>
               </div>
               <div class="timeline-content">
                 <div class="timeline-title">发起申请</div>
                 <div class="timeline-desc">申请退住</div>
                 <div class="timeline-user">{{ form.applyName || '未知用户' }} (已发起)</div>
                 <div class="timeline-time">{{ form.applyTime || '-' }}</div>
               </div>
             </div>
             
             <div class="timeline-item" :class="isRejected ? 'rejected' : 'processing'">
               <div class="timeline-dot">
                 <el-icon :color="isRejected ? '#f56c6c' : '#409eff'" size="16">
                   <Close v-if="isRejected" />
                   <Clock v-else />
                 </el-icon>
               </div>
               <div class="timeline-content">
                 <div class="timeline-title">审批处理</div>
                 <div class="timeline-desc">{{ isRejected ? '申请审批（已拒绝）' : '申请审批' }}</div>
                 <div class="timeline-user">{{ isRejected ? (form.approver || currentUser) + ' (已拒绝)' : currentUser + ' (审批中)' }}</div>
                 <div class="timeline-time">{{ isRejected ? (form.approveTime || '已拒绝') : '等待处理中...' }}</div>
                 <div class="timeline-opinion" v-if="isRejected && approvalForm.approvalOpinion">
                   <div class="timeline-opinion-label">拒绝原因：</div>
                   <div class="timeline-opinion-text">{{ approvalForm.approvalOpinion }}</div>
                 </div>
               </div>
             </div>
           </div>
         </el-card>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <el-button @click="handleBack" size="default">返回</el-button>
      <el-button v-if="!isRejected" type="primary" @click="handleSubmit" size="default">提交</el-button>
    </div>
  </div>


</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Check, Clock, Close } from '@element-plus/icons-vue';
import { addContent, getContent } from '@/api/drop/content';
import useUserStore from '@/store/modules/user';
import { getAccraditationrecordByDropContentId, updateAccraditationrecord } from '@/api/accraditationrecord/accraditationrecord';
import { getUser } from '@/api/system/user';
import { useRouter } from 'vue-router';

const roleName = ref('');

// 路由实例
const router = useRouter();

// 接收父组件传递的参数
const props = defineProps({
  stepNum: {
    type: Number,
    default: 2,
    required: true
  },
  dropContentId: {
    type: [String, Number],
    default: '',
    required: true
  }
});

// 向父组件传递事件
const emit = defineEmits(['submit-step', 'back-to-list']);

// 当前登录用户信息
const userStore = useUserStore();
const currentUser = ref(userStore.nickName || '管理员');

// 步骤一传递的基础数据
const form = ref({});

// 审批表单数据
const approvalForm = ref({
  approvalResult: '',
  approvalOpinion: ''
});
const approvalFormRef = ref(null);

// 是否已拒绝状态
const isRejected = ref(false);

// 获取当前时间格式化
const getCurrentTimeFormatted = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 加载步骤一的数据
const fetchContentDetail = async () => {
  // 若ID为空，直接提示（防止无效请求）
  if (!props.dropContentId) {
    ElMessage.error('未获取到有效的申请ID，请返回上一步重新提交');
    return;
  }

  try {
    const res = await getContent(props.dropContentId);
    if (res.data?.currentInfo) {
      const currentInfo = JSON.parse(res.data.currentInfo);
      form.value = currentInfo;

      // 回显历史审批信息（如驳回后重新审批）
      if (currentInfo.approvalResult) {
        approvalForm.value.approvalResult = currentInfo.approvalResult;
        
        // 检查是否为拒绝状态
        if (currentInfo.approvalResult === 'approvalReject' || currentInfo.approvalResult === '拒绝') {
          isRejected.value = true;
        }
      }
      if (currentInfo.approvalOpinion) {
        approvalForm.value.approvalOpinion = currentInfo.approvalOpinion;
      }
    } else {
      ElMessage.warning('未获取到有效的申请信息');
    }
  } catch (error) {
    console.error('获取详情失败：', error);
    ElMessage.error('获取申请信息失败，请重试');
  }
};

// 格式化退住原因
const formatReason = (reason) => {
  const reasonMap = {
    'personal': '个人原因',
    'recovery': '身体康复',
    'dissatisfaction': '服务不满意',
    'other': '其他原因'
  };
  return reasonMap[reason] || reason;
};

// 表单验证（暴露给父组件）
const validateForm = async () => {
  if (!approvalFormRef.value) return false;
  try {
    await approvalFormRef.value.validate();
    return true;
  } catch (error) {
    ElMessage.warning('请完善审批结果和审批意见');
    return false;
  }
};

// 暴露验证方法
defineExpose({
  validateForm
});

// 返回按钮
const handleBack = () => {
  emit('back-to-list');
};

// 提交审批信息
const handleSubmit = async () => {
  // 1. 验证表单
  const isValid = await validateForm();
  if (!isValid) return;

  try {
    // 2. 合并数据（步骤一数据 + 步骤二审批信息）
    const submitInfo = {
      ...form.value,
      approvalResult: approvalForm.value.approvalResult,
      approvalOpinion: approvalForm.value.approvalOpinion,
      approver: currentUser.value, // 审批人
      approveTime: new Date().toISOString().slice(0, 19).replace('T', ' ') // 审批时间
    };

    // 3. 调用接口保存
    const response = await addContent({
      currentInfo: JSON.stringify(submitInfo)
    });

    // 4. 检查是否为拒绝
    const isRejectResult = approvalForm.value.approvalResult === 'approvalReject';

    if (response.code === 200 && response.dropContentId) {
      // 更新审批表
      const approvalRecords = await getAccraditationrecordByDropContentId(props.dropContentId);
      
      const updateRecord = {
        id: approvalRecords.data.id,
        dropContentId: response.dropContentId,
        currentStep: "申请审批",
        approverName: currentUser.value,
      };

      // 如果是拒绝，设置拒绝相关字段，并保持stepNo为2
      if (isRejectResult) {
        updateRecord.nextStep = "已拒绝";
        updateRecord.stepNo = "2"; // 不再往下一步骤走
        updateRecord.handleType = "已拒绝";
        updateRecord.auditStatus = "拒绝";
        updateRecord.opinion = approvalForm.value.approvalOpinion;
        updateRecord.finishTime = getCurrentTimeFormatted();
      } else {
        // 正常通过，继续下一步
        updateRecord.nextStep = "解除合同";
        updateRecord.stepNo = "3";
      }

      // 更新审批记录
      await updateAccraditationrecord(updateRecord);

      // 如果是拒绝，直接返回列表页
      if (isRejectResult) {
        ElMessage.success('审批拒绝已提交');
        router.push('/togetherwork/togetherwork1/accraditationrecord');
      } else {
        // 正常通过，继续流程
        emit('submit-step', {
          newDropContentId: response.dropContentId,
          currentStep: props.stepNum
        });
        ElMessage.success('审批信息提交成功');
        router.go(-1);
      }
    } else {
      ElMessage.error(`提交失败：${response.msg || '未返回有效ID'}`);
    }

  } catch (error) {
    console.error('提交失败：', error);
    ElMessage.error('提交失败，请检查网络');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  getUser(userStore.id).then(res => {
    if (res.code === 200) {
      roleName.value = res.data.roles[0].roleName;
    }
  })
  console.log('步骤二接收参数：', {
    stepNum: props.stepNum,
    dropContentId: props.dropContentId
  });
  fetchContentDetail();
});
</script>

<style scoped>
.other .ca{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80px;
}

.other h3 {
  margin-top: 20px;
}

.other .operation-record-card {
  margin-top: 30px;
  width: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: auto;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.record-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.record-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.processing {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.record-timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  position: relative;
}

.timeline-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 12px;
  top: 32px;
  width: 2px;
  height: calc(100% + 4px);
  background-color: #e4e7ed;
}

.timeline-item.completed:not(:last-child)::after {
  background-color: #67c23a;
}

.timeline-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
  position: relative;
  z-index: 1;
}

.timeline-item.completed .timeline-dot {
  background-color: #f0f9ff;
  border: 2px solid #67c23a;
}

.timeline-item.processing .timeline-dot {
  background-color: #f0f9ff;
  border: 2px solid #409eff;
}

.timeline-content {
  flex: 1;
  padding-top: 2px;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.timeline-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 6px;
}

.timeline-user {
  font-size: 13px;
  color: #999;
  margin-bottom: 4px;
}

.timeline-time {
  font-size: 12px;
  color: #999;
}

.other img {
  width: 60px;
  height: 60px;
}

.oth {
  color: #333;
  font-size: 14px;
}

.approval-page {
  padding: 20px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-content {
  flex: 2;
}

.right-content {
  flex: 1;
}

.basic-info-card,
.apply-info-card,
.approval-result-card,
.operation-record-card {
  margin-bottom: 20px;
}

.operation-record-card {
  height: 440px;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.label {
  width: 120px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.view-link {
  color: #409eff;
  cursor: pointer;
  margin-left: 8px;
}

.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
}

.record-icon {
  margin-right: 10px;
  margin-top: 2px;
}

.record-content {
  flex: 1;
  color: #333;
}

.record-content p {
  margin: 4px 0;
}

.record-time {
  width: 150px;
  text-align: right;
  color: #999;
}

.bottom-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

/* 拒绝状态样式 */
.rejected-card {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
}

.rejected-record-card {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
}

.status-badge.rejected {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.timeline-item.rejected .timeline-dot {
  background-color: #fef0f0;
  border: 2px solid #f56c6c;
}

.timeline-item.rejected:not(:last-child)::after {
  background-color: #f56c6c;
}

.timeline-opinion {
  margin-top: 12px;
  padding: 12px;
  background-color: #fef0f0;
  border-left: 3px solid #f56c6c;
  border-radius: 4px;
}

.timeline-opinion-label {
  font-size: 13px;
  color: #f56c6c;
  margin-bottom: 6px;
  font-weight: 600;
}

.timeline-opinion-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}
</style>